//
//  LSZPersonalInformationVC.m
//  JK九酷云头条
//
//  Created by 九酷 on 2017/11/22.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LSZPersonalInformationVC.h"

@interface LSZPersonalInformationVC ()

@end

@implementation LSZPersonalInformationVC
-(void)viewWillAppear:(BOOL)animated
{
    NSString * str = [NSString stringWithFormat:@"%@/user/get_info",URLTotal];
    NSDictionary * dic = [[NSDictionary alloc]init];
    [LSZRequestData initregistrationSendVerificationCode:dic url:str :^(BOOL isOK, NSString * str, NSDictionary * dic) {
        if (isOK == YES) {
            self.stringUserName = [NSString stringWithFormat:@"%@",dic[@"data"][@"username"]];
            self.uid = [NSString stringWithFormat:@"%@",dic[@"data"][@"uid"]];
//            self.wx_bind = [NSString stringWithFormat:@"%@",dic[@"data"][@"wx_bind"]];
//            self.credit = [NSString stringWithFormat:@"%@",dic[@"data"][@"credit"]];
//            self.cash = [NSString stringWithFormat:@"%@",dic[@"data"][@"cash"]];
            [self.tableViewMy reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:dic[@"msg"]];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    [self setUiInformation];
}
-(void)setUiInformation
{
    self.view.backgroundColor = RGBColor(247, 247, 247);
    self.arrayTitle = @[@"昵称"];
    [self.tableViewMy registerClass:[LSZInformationTableViewCell class] forCellReuseIdentifier:@"LSZInformationTableViewCell"];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayTitle.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZInformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZInformationTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[LSZInformationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LSZInformationTableViewCell"];
    }
    
//    LSZPersonalInformationMg * manager = nil;
//    manager = self.informationManager.mutDataArray[0];
    
    cell.labelTitle.text = [NSString stringWithFormat:@"%@",self.arrayTitle[indexPath.row]];
//    if (indexPath.row == 0) {
//        cell.imageViewPhoto.hidden = NO;
//        cell.labelName.hidden = YES;
////        NSString * avatar = NullStringjudgment(manager.avatar);
////        if([avatar isEqualToString:@""]){
////            cell.imageViewPhoto.image = [UIImage imageNamed:@"placeholder"];
////        }else{
////            NSString * State = [[NSUserDefaults standardUserDefaults]objectForKey:@"headerPhoto"];
////
////            [cell.imageViewPhoto sd_setImageWithURL:[NSURL URLWithString:State] placeholderImage:[UIImage imageNamed:@"placeholder"]];
////        }
//    }
    if (indexPath.row == 0 ) {
        cell.imageViewPhoto.hidden = YES;
        cell.labelName.hidden = NO;
        if ( [self.stringUserName  isEqualToString:@""] ||[self.stringUserName isEqualToString:@"(null)"]||self.stringUserName == nil || self.stringUserName == NULL||[self.stringUserName isKindOfClass:[NSNull class]]||[[self.stringUserName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
            if ( [self.uid  isEqualToString:@""] ||[self.uid isEqualToString:@"(null)"]||self.uid == nil || self.uid == NULL||[self.uid isKindOfClass:[NSNull class]]||[[self.uid stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
                cell.labelName.text = [NSString stringWithFormat:@"还没填写昵称"];
            }else{
                   cell.labelName.text = [NSString stringWithFormat:@"jk_%@",self.uid];
            }
        }else{
            cell.labelName.text = [NSString stringWithFormat:@"%@", self.stringUserName];//username
        }
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row == 0) {
//        //修改头像
//        [self ModifyThePicture];
//    }
    if(indexPath.row == 0){
        //修改昵称
        LSZNicknameVC * VC= [[LSZNicknameVC alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    }
}
#pragma mark - 修改头像
-(void)ModifyThePicture
{
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *showAllInfoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self initWithPhoneFromThePhotoAlbum];
    }];
    UIAlertAction *pickAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self initWithPhoneTakingpictures];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [actionSheetController addAction:cancelAction];
    [actionSheetController addAction:pickAction];
    [actionSheetController addAction:showAllInfoAction];
    
    [self presentViewController:actionSheetController animated:YES completion:nil];
}
#pragma mark - 拍照
-(void)initWithPhoneTakingpictures
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相机
        sourceType = UIImagePickerControllerSourceTypeCamera;
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            //            [self initWithSetUpJumpAlert:@"摄像头访问受限,请打开摄像头允许拍摄!"];
            return;
        }
 
    }
    else {
        //        [BaseViewController initwithAlert:@"此设备没有摄像功能!"];
        return;
    }
    
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = NO;//没有裁剪框
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}
#pragma mark - 从相册里面查找
-(void)initWithPhoneFromThePhotoAlbum
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相册//来自图库
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
        {
            //无权限
            //            [self initWithSetUpJumpAlert:@"照片访问受限,请打开app访问你的照片!"];
            return;
        }
    }
    else {
        //来自相册
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
        {
            //无权限
            //            [self initWithSetUpJumpAlert:@"照片访问受限,请打开app访问你的照片!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = NO;//没有裁剪框
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    //UIImagePickerControllerMediaURL
    //    NSURL * videoUrl = [info objectForKey:UIImagePickerControllerReferenceURL];
    //    NSLog(@"%@<><>",videoUrl);
    UIImage *imagestr = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    if(result == YES ){
        //需要在此处上传服务器
//        __weak typeof(self) weakSelf = self;
//        [LSZRequestData initWithModifyThePicture:imagestr filePath:filePath :^(BOOL isOk, NSString * str, NSDictionary * dic) {
//            if(isOk == YES){
//                NSString * urlStr = dic[@"data"];
//                LSZInformationTableViewCell * cell = (LSZInformationTableViewCell *)[weakSelf.tableViewMy cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
//                cell.imageViewPhoto.image = imagestr;
//                [weakSelf LinkStorageOfImages:urlStr];
//            }else{
//                [self addHubPromptMessage:str];
//            }
//        }];
    }
}
#pragma mark - 把上传的图片的链接存储在本地
-(void)LinkStorageOfImages :(NSString *)url
{
    //    获取当前时间的毫秒数
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    NSString * date = [formatter stringFromDate:[NSDate date]];
    NSString * timeNow = [[NSString alloc] initWithFormat:@"%@", date];
    //八位随机数
    NSString * strRandom = @"";
    for (int i=0; i<3; i++) {
        strRandom = [strRandom stringByAppendingFormat:@"%i",(arc4random() % 9)];
    }
    //   avatar 头像
    NSString * imageNameStr = [NSString stringWithFormat:@"%@?%@%@",url,timeNow,strRandom];
    NSLog(@"%@",imageNameStr);
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:imageNameStr forKey:@"headerPhoto"];
}
-(UITableView *)tableViewMy
{
    if (_tableViewMy == nil) {
        _tableViewMy = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
        _tableViewMy.dataSource = self;
        _tableViewMy.delegate = self;
        //添加以下代码关闭估算行高
        _tableViewMy.estimatedRowHeight = 0;
        _tableViewMy.estimatedSectionHeaderHeight = 0;
        _tableViewMy.estimatedSectionFooterHeight = 0;
        //如果没有占满则清除下面的
        _tableViewMy.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [_tableViewMy setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
        [self.view addSubview:_tableViewMy];
    }
    return _tableViewMy;
}
@end
